package org.apache.ocean.nio;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ocean.HttpParameters;
import org.apache.ocean.HttpRequest;
import org.apache.ocean.HttpResponse;
import org.apache.ocean.OceanXML;
import org.apache.ocean.TimeoutState;
import org.apache.ocean.XMLUtil;
import org.apache.ocean.OceanXML.RequestException;
import org.apache.ocean.name.Node;

public class OceanNioHttpClient extends NioHttpClient {
	public OceanNioHttpClient(int workerCount) throws Exception {
		super(workerCount);
	}
	
	public static class RequestID {
		public URL url;
		public Object attachment;
		
		public RequestID(Object attachment, URL url) {
			this.attachment = attachment;
			this.url = url;
		}
	}
	
	public static class OceanResponse {
		public Node node;
		public OceanXML oceanXML;
		
		public OceanResponse(Node node, OceanXML oceanXML) {
			this.node = node;
			this.oceanXML = oceanXML;
		}
	}
	
	public Map<String,OceanResponse> requestOceanXMLs(List<RequestID> requestIDs, HttpParameters parameters, TimeoutState timeoutState) throws RequestException, Exception {
		List<HttpRequest> httpRequests = new ArrayList<HttpRequest>();
		for (RequestID requestID : requestIDs) {
			HttpRequest httpRequest = new HttpRequest(requestID.attachment, requestID.url, parameters);
			httpRequests.add(httpRequest);
		}
		List<HttpResponse> httpResponses = request(httpRequests, timeoutState);
		Map<String,OceanResponse> oceanResponses = new HashMap<String,OceanResponse>(httpResponses.size());
		for (HttpResponse httpResponse : httpResponses) {
			String responseXML = httpResponse.getBodyString();
			OceanXML oceanXML = new OceanXML(XMLUtil.parseElement(responseXML));
			OceanXML.throwRequestException(httpResponse.attachment, httpResponse.url, oceanXML);
			Node node = (Node)httpResponse.attachment;
			oceanResponses.put(node.assignedCellID, new OceanResponse(node, oceanXML));
		}
		return oceanResponses;
	}
}
